<?php

namespace app\stationapp\controller;

use app\model\UserOrder as ModelUserOrder;
use app\model\StationInfo as ModelStationInfo;
use app\model\StationMemberInfo as ModelStationMemberInfo;
use app\model\StationOrder as ModelStationOrder;
use app\model\StationOrderLog as ModelStationOrderLog;
use app\model\UserOrderLog as ModelUserOrderLog;
use app\model\CourierOrder as ModelCourierOrder;
use app\model\CourierInfo as ModelCourierInfo;
use app\model\CashStream as ModelCashStream;


use think\Db;

/**
 * 订单相关类
 * Class Common
 * @package app\stationapp\controller
 */
class Order extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }


    /*
     * 快件入库---返回订单信息
     * URI：/stationapp.express.info
     */
    public function expressInfo()
    {
        $expressSn = $this->_getContentParams('expressSn');

        _toCompare(empty($expressSn),'==',true,17001);
        //获取订单详情
        $orderInfo = ModelUserOrder::getInstance()->toFind(['express_order_sn'=>$expressSn]);
//        $streetId = json_decode($orderInfo['recipient_info'],true)['streetId'];
//        $countyId = json_decode($orderInfo['recipient_info'],true)['countyId'];
        //始发站点
        $sendStationId = ModelStationMemberInfo::getInstance()->toValue(['id'=>$this->station_member_id],'station_id');
        $sendStationInfo = ModelStationInfo::getInstance()->toFind(['id'=>$sendStationId],'name,lng,lat');
        //到达站点
        $receivedAreaId = $orderInfo['received_area_id'];
        $recStationList = ModelStationInfo::getInstance()->toSelect(['area_id'=>$receivedAreaId]);//到达站点列表
        foreach ($recStationList as $key=>&$value){
            $value['distance'] = $this->getDistance($sendStationInfo['lng'],$sendStationInfo['lat'],$value['lng'],$value['lat']); //站点距离
        }
        //到达站点排序---选择距离最近的站点
        $recStationList = my_sort($recStationList,'distance');

        //返回数据
        $data['sendStationId'] = $sendStationId;
        $data['sendStationName'] = $sendStationInfo['branch_name'];//始发站点名称
        $data['recStationId'] = $recStationList[0]['id'];
        $data['recStationName'] = $recStationList[0]['branch_name'];//到达站点名称
        $data['sendInfo'] = $orderInfo['sender_info'];//寄件信息
        $data['recipientInfo'] = $orderInfo['recipient_info'];//收件信息
        $data['itemWeight'] = $orderInfo['item_weight'];//物品重量
        $data['expressSn'] = $orderInfo['express_order_sn'];//快件单号
        $data['orderId'] = $orderInfo['order_id'];

        _returnData(['info'=>$data]);
    }

    /*
     * 标记异常--取消标记异常
     * URI：/stationapp/express.sign.unusual
     * type:0:标记；1：取消
     */
    public function signUnusual()
    {
        $orderId = $this->_getContentParams('orderId');
        _toValidate('id',$orderId,10009);
        $type = $this->_getContentParams('type');
        _toCompare(in_array($type,[0,1]),'==',false,16006);
        $bool_res = ModelUserOrder::getInstance()->toUpdate(['order_id'=>$orderId],['is_unusual'=>$type]);
        if ($bool_res) _returnData();
        _returnError(16002);
    }
    /*
     * 判断快件是否异常/stationapp.unusual.check
     * URI：
     */
    public function checkIsUnusual()
    {
        $orderId = 149;//$this->_getContentParams('orderId');
        _toValidate('id',$orderId,10009);
        $is_unusual = ModelUserOrder::getInstance()->toValue(['order_id'=>$orderId],'is_unusual');
        _returnData(['isUsual'=>$is_unusual]);
    }

    /*
    * 确定入库
    *
    * URI：/stationapp.express.confirm
    */
    public function expressConfirmIn()
    {
        $volume = '100*100*100';// $this->_getContentParams('volume');
        _toCompare(empty($volume),'==',true,16003);
        $orderId = 149 ;// $this->_getContentParams('orderId');
        _toValidate('id',$orderId,10009);
        $receiveStationId = $this->_getContentParams('receiveStationId');
        _toValidate('id',$receiveStationId,10009);

        //获取站点id
        $stationId = ModelStationMemberInfo::getInstance()->toValue(['id'=>$this->station_member_id],'station_id');
        //获取订单详情
        $orderInfo = ModelUserOrder::getInstance()->toFind(['order_id'=>$orderId]);
        if ($orderInfo['order_state'] == 30){
            //修改用户订单表订单状态
            $update_res = ModelUserOrder::getInstance()->toUpdate(['order_id'=>$orderId],['order_state'=>40]);
            //写入用户订单表日志
            $add_res = ModelUserOrderLog::getInstance()->addOrderLog($orderId,3,$this->station_member_id);
            if ($update_res && $add_res){
                //快递员佣金结算 -- 查找该订单的快递员
                $courierId = ModelCourierOrder::getInstance()->toValue(['order_id'=>$orderId,'is_pick'=>1],'courier_id');
                $courierCommission = ModelCourierInfo::getInstance()->getCommission($courierId,$orderId); //分佣金额
                //修改快递员金额
                $courierAddFee = ModelCashStream::getInstance()->editBalance(1,$courierId,0,$courierCommission,'揽收入库',$orderInfo['order_sn'],$orderId);
                //添加站点订单
                $res = ModelStationOrder::getInstance()->stationOrderAdd($this->station_member_id,$orderInfo['order_id'],1,$receiveStationId);
                //添加站点订单记录
                $log_res = ModelStationOrderLog::getInstance()->stationOrderLogAdd($stationId,$this->station_member_id,$orderId,1);
                //获取站点分佣金额
                $stationCommission = ModelStationInfo::getInstance()->getCommission($stationId,$orderId);
                //修改站点余额
                $stationAddFee = ModelCashStream::getInstance()->editBalance(3,$stationId,'0',$stationCommission,'站点入库分佣',ModelUserOrder::getInstance()->toValue(['order_id'=>$orderId],'order_sn'),$orderId);
                if ($courierAddFee && $stationAddFee && $res && $log_res){
                    _returnData();
                }else{
                    _returnError(16004);
                }
            }
        }elseif($orderInfo['order_state'] == 75){//快递员未在规定时间内配送完成，快件返回站点入库
            //修改用户订单表订单状态
            $update = ModelUserOrder::getInstance()->toUpdate(['order_id'=>$orderId],['order_state'=>40]);
            //写入用户订单表日志
            $add = ModelUserOrderLog::getInstance()->addOrderLog($orderId,3,$this->station_member_id);
            if ($update && $add){
                //修改站点订单表状态
                $up_res = ModelStationOrder::getInstance()->toUpdate(['order_id'=>$orderId,'station_id'=>$stationId],['state'=>ModelUserOrder::getInstance()->toValue(['order_id'=>$orderId],'order_state')]);
                //写入站点订单日志
                $stationLogRes = ModelStationOrderLog::getInstance()->StationOrderLogAdd($stationId,$this->station_member_id,$orderId,ModelStationOrder::getInstance()->toValue(['order_id'=>$orderId],'is_pick'),1,'快递员取消配送，返回站点入库,等待重新出库！');
                //写入用户订单日志
                $userOrderLogRes =ModelUserOrderLog::getInstance()->addOrderLog($orderId,3,$this->station_member_id,'快递员取消配送，返回站点入库,等待重新出库！');
                if ($up_res && $stationLogRes && $userOrderLogRes){
                    _returnData();
                }else{
                    _returnError(16004);
                }
            }
        }else{
            _returnError(16005);

        }
        _returnError(16004);
    }
    /*
     * 快件出库---订单信息
     * URI：/stationapp.express.out.info
     */
    public function expressConfirmOut(){
        $expressSn = $this->_getContentParams('expressSn');
        _toCompare(empty($expressSn),'==',true,12002);
        $orderInfo = ModelUserOrder::getInstance()->toFind(['express_order_sn'=>$expressSn]);
    }

}
